/*
 * PersistenceManagerAbstract.java
 *
 * Created on 15. August 2007, 17:37
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package timeitj.ejb.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;

/**
 *
 * @author kunee
 */
@DeclareRoles({"USERS","ADMINS"})
public abstract class PersistenceManagerAbstract<T, ID extends Serializable> implements PersistenceManager<T, ID> {
    
    @PersistenceContext(unitName="timeitjPU")
    protected EntityManager em;
    
    private Class<T> managedType;
    
    protected static Logger log; 
        
    public PersistenceManagerAbstract(){
        this.managedType = (Class<T>) 
            ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    @RolesAllowed("USERS")
    public void store(T entity) {
        em.persist(entity);
    }
    
    @RolesAllowed("USERS")
    public void delete(T entity) {
        log.info("Removing entity" + entity.toString());
        em.remove(em.merge(entity));
        em.flush();
        log.info("Done");
    }
    
    @RolesAllowed("USERS")
    public T getById(ID id) {
        return (T) em.find(managedType.getClass(), id);
    }
    
    @RolesAllowed("USERS")
    public T update(T entity){
        em.merge(entity);
        return entity;
    }
    
    @PermitAll
    public T create(T entity){
        em.persist(entity);
        // TODO: vermutlich kein Performance-Hit!
        em.flush();
        em.refresh(entity);
        return entity;
    }
    
}
